﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Media;
using NetBay.Core.BusinessEntities;
using Rio.Applications.Web.Services;

namespace Rio.Framework.Pages.CriteriaControls
{
    public partial class ListOjectIndexControl 
    {

        private List<ObjectValue> m_oListObjectValue;
        public event EventHandler SelectionChanged;

        /// <summary>
        /// Get or set the control value
        /// </summary>
        public override string InputValue
        {
            get
            {
                if (ComboboxInput.SelectedItem != null)
                {
                    if (ComboboxInput.SelectedItem is ObjectValue)
                    {
                        return ( (ObjectValue)ComboboxInput.SelectedItem ).Name;
                    }
                    return ComboboxInput.SelectedItem as string;
                }
                return String.Empty;
            }
            set
            {
                if (m_oListObjectValue.Where(e => e.Name.Equals(value)).FirstOrDefault() != null)
                {
                    if (m_oListObjectValue != null && m_oListObjectValue.Count > 0)
                    {
                        ComboboxInput.SelectedItem = m_oListObjectValue.Where(e => e.Name.Equals(value)).First();
                    }
                }
                else
                {
                    ComboboxInput.SelectedIndex = -1;
                }
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ListOjectIndexControl"/> class.
        /// </summary>
        public ListOjectIndexControl()
        {
            InitializeComponent();

            InitLabel();

            _originalBorderBrush = this.ComboboxInput.BorderBrush as SolidColorBrush;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ListOjectIndexControl"/> class.
        /// </summary>
        /// <param name="P_oIndex">Index of the p_o.</param>
        /// <param name="P_lFolderTypeIdentifier">The P_L folder type identifier.</param>
        /// <param name="P_lSelectValueIdentifier">The P_L select value identifier.</param>
        /// <param name="P_SetDefaultValue">if set to <c>true</c> [p_ set default value].</param>
        public ListOjectIndexControl(Index P_oIndex, long P_lFolderTypeIdentifier, long? P_lSelectValueIdentifier = null, bool P_SetDefaultValue = false)
            : this()
        {
            CurrentIndex = P_oIndex;
            LabelControl.Text = CurrentIndex.IndexLabel;

            m_oListObjectValue = new List<ObjectValue>();

            //Mandatory indication
            LabelMandatory.Visibility = CurrentIndex.IsMandatory ? Visibility.Visible : Visibility.Collapsed;

                GUIDomainContext l_oGUIDDomainContext = new GUIDomainContext();

                l_oGUIDDomainContext.GetIndexValueList(
                    P_lFolderTypeIdentifier,
                    CurrentIndex.IndexOrder,
                    delegate(InvokeOperation<Dictionary<long, string>> listValue)
                    {
                        if (( listValue != null ) && ( listValue.Value != null ))
                        {
                            foreach (KeyValuePair<long, string> l_oKvp in listValue.Value)
                            {
                                m_oListObjectValue.Add(new ObjectValue
                                                           {
                                    Identifier = l_oKvp.Key,
                                    Name = l_oKvp.Value
                                });
                            }
                        }

                        ComboboxInput.ItemsSource = m_oListObjectValue;
                        ComboboxInput.DisplayMemberPath = "Name";

                        //setdefaut if needed
                        if (P_SetDefaultValue)
                            this.SetDefaultValue();

                        //When items are filled, we selected the item (it used when a search by uri)
                        if (!String.IsNullOrWhiteSpace(SelectedValueAfterInit))
                        {
                            ComboboxInput.SelectedItem = ComboboxInput.Items.Cast<ObjectValue>().Where(item => item.Name == SelectedValueAfterInit).FirstOrDefault();
                        }

                        //A value is selected at the start
                        if (P_lSelectValueIdentifier != null && P_lSelectValueIdentifier != -1)
                        {
                            if (m_oListObjectValue.Where(e => e.Identifier.Equals(P_lSelectValueIdentifier)).FirstOrDefault() != null)
                            {
                                ComboboxInput.SelectedItem = m_oListObjectValue.Where(e => e.Identifier.Equals(P_lSelectValueIdentifier)).First();
                            }
                            else
                            {
                                ComboboxInput.SelectedIndex = -1;
                            }
                        }
                    },
                    false);

                FilterButton.Visibility = Visibility.Visible;
        }

        /// <summary>
        /// Sets the index by text.
        /// </summary>
        /// <param name="selectValueAsText">The P_L select value as text.</param>
        public override void SetIndexByText(string selectValueAsText)
        {
            if (!string.IsNullOrEmpty(selectValueAsText))
            {
                m_oListObjectValue = new List<ObjectValue>();

                ObjectValue l_oObject = new ObjectValue
                                            {
                    Identifier = 0,
                    Name = selectValueAsText
                };
                m_oListObjectValue.Add(l_oObject);

                ComboboxInput.ItemsSource = m_oListObjectValue;
                ComboboxInput.DisplayMemberPath = "Name";
                ComboboxInput.SelectedItem = l_oObject;
            }
        }

        /// <summary>
        /// Display filter window with a list of values input
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void buttonInput_Click(object sender, RoutedEventArgs e)
        {
            OnFilterClick(new Events.FilterClickEventArgs(this.CurrentIndex));
        }


        /// <summary>
        /// Handles the Click event of the buttonDelete control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void buttonDelete_Click(object sender, RoutedEventArgs e)
        {
            OnRemoveControlClick(new EventArgs());
        }

        /// <summary>
        /// Must be override in child class
        /// </summary>
        public override sealed void InitLabel()
        {
            base.InitLabel();
            ComboboxInput.ClearSelectionButtonContent = "Effacer";
        }

        /// <summary>
        /// Used to clear value
        /// </summary>
        public override void Clear()
        {
            ComboboxInput.SelectedIndex = -1;
        }

        /// <summary>
        /// Throw validation event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ComboboxInput_LostFocus(object sender, RoutedEventArgs e)
        {
            OnValueValidated(EventArgs.Empty);
        }

        /// <summary>
        /// Throw validation event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ComboboxInput_SelectionChanged(object sender, Telerik.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (SelectionChanged != null)
            {
                SelectionChanged(this, e);
            }
            else
            {
                OnValueValidated(EventArgs.Empty);
            }
        }

        /// <summary>
        /// Invoke the value validated event; called whenever a value is svalidated
        /// </summary>
        /// <param name="e"></param>
        protected void OnSelectionChanged(EventArgs e)
        {
            OnValueValidated(EventArgs.Empty);
        }

        /// <summary>
        /// Used to set border color of input control
        /// </summary>
        public override void ChangeBorderColor(Color color)
        {
            this.ComboboxInput.BorderBrush = new SolidColorBrush(color);
        }

        public override void RevertBorderColor()
        {
            this.ComboboxInput.BorderBrush = _originalBorderBrush;
        }

        /// <summary>
        /// Set the max lenght of the control
        /// </summary>
        public override void SetMaxLength()
        {
        }

        /// <summary>
        /// Hide mandatory label
        /// </summary>
        public override void DisableMandatoryLabel()
        {
            this.LabelMandatory.Visibility = Visibility.Collapsed;
        }

        /// <summary>
        /// Hides Index label name
        /// </summary>
        public override void DisableIndexLabel()
        {
            this.LabelControl.Visibility = Visibility.Collapsed;
        }

        /// <summary>
        /// Activate Removing feature
        /// </summary>
        public override void ActiveRemove()
        {
            this.DeleteButton.Visibility = Visibility.Visible;
        }

        /// <summary>
        /// Hides filter button
        /// </summary>
        public override void DisableFilter()
        {
            this.FilterButton.Visibility = Visibility.Collapsed;
        }
    }

    public class ObjectValue
    {
        public long Identifier { get; set; }
        public string Name { get; set; }
    }
}
